<template>
  <div class="flex flex-col items-center justify-center mt-8 space-y-4">
    <!-- 授权加载中 -->
    <div v-if="loading" class="flex items-center justify-center h-32">
      <el-icon class="animate-spin mr-2 text-primary">
        <Loading />
      </el-icon>
      <span class="text-gray-500">正在跳转微信授权...</span>
    </div>

    <!-- 授权失败 -->
    <div v-else-if="errorMsg" class="text-center text-red-500 space-y-4 mt-8">
      <p>{{ errorMsg }}</p>
      <el-button
        type="primary"
        size="small"
        @click="fetchOAuthAuth"
        :loading="loading"
      >
        重试授权
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { Loading } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { wxauth, wxauthCallback } from "../api/index.js";

// 1. 新增：接收父组件传递的autoTrigger参数（微信内自动触发授权）
// 显式声明接收 auto-trigger 属性
const props = defineProps({
  redirect: {
    type: String,
    default: "/index"
  },
  autoTrigger: { // 关键：声明autoTrigger属性
    type: Boolean,
    default: false // 默认不自动触发
  }
});

// 对外暴露事件
const emit = defineEmits(["login-success"]);

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const errorMsg = ref("");
const isFirstLoad = ref(true); // 新增：标记是否首次加载

onMounted(async () => {
  // 2. 修复核心逻辑：微信内首次加载且autoTrigger=true时，自动触发授权
  if (props.autoTrigger && isFirstLoad.value) {
    // 检查是否为回调（有code参数），是则处理回调，否则发起授权
    const code = route.query.code || new URLSearchParams(window.location.search).get("code");
    const state = route.query.state || new URLSearchParams(window.location.search).get("state");
    
    if (code && state) {
      await handleOAuthCallback(code, state);
    } else {
      await fetchOAuthAuth(); // 微信内首次加载，自动发起授权
    }
    isFirstLoad.value = false; // 标记为非首次加载
  } else {
    // 非自动触发场景（如手动重试），保留原有逻辑
    const code = route.query.code || new URLSearchParams(window.location.search).get("code");
    const state = route.query.state || new URLSearchParams(window.location.search).get("state");
    if (code && state) {
      await handleOAuthCallback(code, state);
    }
  }
});

/**
 * 发起微信OAuth授权（原有逻辑不变）
 */
async function fetchOAuthAuth() {
  try {
    loading.value = true;
    errorMsg.value = "";

    const res = await wxauth(); // 调用后端/wechat/v1/auth接口
    if (res.code === 200 && res.data?.qr_url) {
      window.location.href = res.data.qr_url; // 跳转到微信授权页
    } else {
      errorMsg.value = res.msg || "获取授权地址失败，请重试";
    }
  } catch (e) {
    console.error("发起OAuth授权失败:", e);
    errorMsg.value = "网络异常，授权发起失败";
  } finally {
    loading.value = false;
  }
}

/**
 * 处理微信授权回调（原有逻辑不变）
 */
async function handleOAuthCallback(code, state) {
  try {
    loading.value = true;
    errorMsg.value = "";

    const res = await wxauthCallback({
      code,
      state,
      redirect: props.redirect,
    });

    if (res.code === 200) {
      const { token, nickname, headimgurl, openid } = res.data || {};
      emit("login-success", { token, nickname, headimgurl, openid });
      clearCallbackParams();
    } else {
      errorMsg.value = res.msg || "微信授权失败，请重试";
    }
  } catch (e) {
    console.error("处理OAuth回调失败:", e);
    errorMsg.value = "网络异常，授权结果处理失败";
  } finally {
    loading.value = false;
  }
}

/**
 * 清理URL中的回调参数（原有逻辑不变）
 */
function clearCallbackParams() {
  const { query, path } = route;
  const cleanedQuery = { ...query };
  delete cleanedQuery.code;
  delete cleanedQuery.state;

  router.replace({ path, query: cleanedQuery });
  window.history.replaceState(
    null,
    "",
    `${window.location.pathname}${Object.keys(cleanedQuery).length ? `?${new URLSearchParams(cleanedQuery)}` : ""}${window.location.hash}`
  );
}
</script>